import { Component } from "react";
import React from "react";
import {
  Cell,
  Form,
  Button,
  InputNumber,
  Input,
  TextArea,
  Picker,
  Radio,
  Checkbox,
  DatePicker,
} from "@nutui/nutui-react-taro";
import styles from "./index.scss";
import { useModel } from "@/store";
import ComponentLayout from "@/components/ComponentLayout";
import { InsertPatInfo, addPatInfo, queryPatInfo } from "@/services/patInfo";
import { useState } from "react";
import { useRef } from "react";
import Taro from "@tarojs/taro";
import Layout from "@/components/Layout";
// import { Empty } from '@nutui/nutui-react-taro';

const pickerOptions = [
  {
    value: "01",
    text: "居民身份证",
  },
  {
    value: "02",
    text: "居民户口簿",
  },
  {
    value: "03",
    text: "护照",
  },
  {
    value: "04",
    text: "军官证",
  },
  {
    value: "05",
    text: "驾驶证",
  },
  {
    value: "06",
    text: "港澳居民来往内地通行证",
  },
  {
    value: "07",
    text: "台湾居民来往内地通行证",
  },
  {
    value: "99",
    text: "其他有效证件",
  },
];
// comm_credentials_type_dict证件类型表
// 01：居民身份证
// 02：居民户口簿
// 03：护照
// 04：军官证
// 05：驾驶证
// 06：港澳居民来往内地通行证
// 07：台湾居民来往内地通行证
// 99：其他有效证件

let datePickerStartDate = new Date(); // 创建一个表示当前日期和时间的Date对象
datePickerStartDate.setFullYear(datePickerStartDate.getFullYear() - 100); // 将年份设置为100年前的年份

function getBirthDateFromIDCard(idCard) {
  // 检查身份证号码长度是否为18位
  if (idCard.length !== 18) {
    throw new Error("身份证号码必须为18位");
  }

  // 提取出生日期部分
  const birthDateStr = idCard.substring(6, 14);

  // 将字符串转换为Date对象
  const year = birthDateStr.substring(0, 4);
  const month =birthDateStr.substring(4, 6);
  const day =birthDateStr.substring(6, 8)


return year + '-' + month + '-' + day 

}


function getGenderFromIdCard(idCard) {
  if (idCard.length !== 18) {

    return null
  }
  const genderDigit = parseInt(idCard.charAt(16), 10);
  return genderDigit % 2 === 1 ? '1' : '2';
}

export default () => {
  const [datePickerVisible, setDatePickerVisible] = useState(false);
  const [agreChecked, setAgreChecked] = useState(false);

  const [form] = Form.useForm();
  const { user } = useModel("user");
  const { getPatientList, setCurPatientInfo } = useModel("patient");
  const ref = useRef({ checkHisPatInfo: {} });
  const submitSucceed = async (values) => {
    if (!agreChecked) {
      Taro.showToast({
        title: "请先阅读并勾选用户协议",
        icon: "none",
      });
      return;
    }

    const { checkHisPatInfo } = ref.current;

    const { credentialsType, ...otherValues } = values;
    // // checkHisPatInfo有数据表示his有这个人的数据，直接关联就诊人
    // if(ref.current.checkHisPatInfo?.patientId === values.patientId){

    // }

    // const credentialsType:
    //添加人员到his
    const res = await InsertPatInfo({
      ...checkHisPatInfo,
      ...otherValues,
      credentialsType: credentialsType[0],
    });
    setCurPatientInfo({
      ...checkHisPatInfo,
      ...otherValues,
      credentialsType: credentialsType[0],
      patientId: res.patientId,
    });

    // Taro.setStorage({
    //   key: "defPatientInfo",
    //   data: {
    //     ...checkHisPatInfo,
    //     ...otherValues,
    //     credentialsType: credentialsType[0],
    //     patientId: res.patientId,
    //   },
    // });
    // 关联就诊人
    addPatInfo({
      ...checkHisPatInfo,
      ...otherValues,
      credentialsType: credentialsType[0],
      patientId: res.patientId,
    }).then(() => {
      getPatientList(user);
      Taro.showToast({
        title: "添加成功",
        icon: "none",
        complete: () => {
          Taro.navigateBack({
            delta: 1,
          });
        },
      });
    });
  };

  const checkHisPatInfo = (value) => {
    // const  form.getFieldValue('')
    ref.current.checkHisPatInfo = {};

    if (form.getFieldValue("credentialsType") == "01") {
      const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9X]$/;

      // 验证身份证号码是否符合正则表达式
      if (!idCardRegex.test(value)) {
        Taro.showToast({
          title: "身份证号错误，请重新输入",
          icon: "none",
        });
        return;
      }
    }

    queryPatInfo({ queryType: "2", queryNo: value }).then((res) => {
    
      if (res.patientId) {
        // if(res.)
        form.setFieldsValue({
          patientName: res.patientName,
          sex: res.sex,
          dateOfBirth: res.dateOfBirth,
          homePhone: res.homePhone,
        });

        ref.current.checkHisPatInfo = res;
      }

      if (!res.dateOfBirth && form.getFieldValue("credentialsType") == "01") {
        const birth = getBirthDateFromIDCard(value);
        const sex = getGenderFromIdCard(value);
        
        console.log(birth, "birth");
        form.setFieldsValue({
          dateOfBirth: birth,
          sex:sex
        });
      }
    }).catch(err=>{
       
         if (!res.dateOfBirth && form.getFieldValue("credentialsType") == "01") {
        const birth = getBirthDateFromIDCard(value);
        const sex = getGenderFromIdCard(value);
        
        console.log(birth, "birth");
        form.setFieldsValue({
          dateOfBirth: birth,
          sex:sex
        });
      }
    });
  };


  return (
    <Layout title="添加就诊人">
      <view className={styles.addPatientWarp}>
        {/* <view className="card"> */}
        <view>
          <Form
            form={form}
            labelPosition="left"
            initialValues={{ credentialsType: ["01"], sex: "1" }}
            onFinish={(values) => submitSucceed(values)}
            // onFinishFailed={(values, errors) => submitFailed(errors)}
            footer={
              <view
                style={{
                  display: "flex",
                  flexDirection: "column",
                  width: "100%",
                }}
              >
                <Checkbox
                  checked={agreChecked}
                  onChange={(e) => {
             
                    setAgreChecked(e);
                  }}
                  style={{
                    marginBottom: "10px",
                    marginTop: "20px",
                    "--nutui-checkbox-label-font-size": "12px",
                  }}
                >
                  <view>
                    我已阅读并同意
                    <view
                      onClick={(e) => {
                        e.stopPropagation();
                        Taro.navigateTo({
                          url: "/pages/userAgreement/index",
                        });
                      }}
                      style={{ display: "inline", color: "red" }}
                    >
                      {"<用户服务协议>"}
                    </view>
                    和
                    <view
                      onClick={(e) => {
                        e.stopPropagation();
                        Taro.navigateTo({
                          url: "/pages/privacyPolicy/index",
                        });
                      }}
                      style={{ display: "inline", color: "red" }}
                    >
                      {"<隐私政策>"}
                    </view>
                  </view>
                </Checkbox>
                <view style={{ width: "100%" }}>
                  <Button
                    formType="submit"
                    block
                    shape={null}
                    type="info"
                    style={{ width: "100%" }}
                  >
                    添加就诊人
                  </Button>
                </view>
              </view>
            }
          >
            <Form.Item
              label="姓名"
              name="patientName"
              rules={[{ required: true, message: "请输入姓名" }]}
            >
              <Input placeholder="请输入姓名" type="text" />
            </Form.Item>
            <Form.Item
              label="证件类型"
              name="credentialsType"
              trigger="onConfirm"
              getValueFromEvent={(...args) => args[1]}
              onClick={(event, ref) => {
         
                ref.open();
              }}
              initialValue={["01"]}
            >
              <Picker options={[pickerOptions]}>
                {(value) => {
                  // console.log(value, value.length, "pickerOptions ");
                  return (
                    <Cell
                      style={{
                        padding: 0,
                        "--nutui-cell-divider-border-bottom": "0",
                      }}
                      className="nutui-cell--clickable"
                      title={
                        value.length
                          ? pickerOptions.filter(
                              (po) => po.value === value[0]
                            )[0]?.text
                          : "Please select"
                      }
                      // extra={<ArrowRight />}
                      align="center"
                    />
                  );
                }}
              </Picker>
            </Form.Item>
            <Form.Item label="证件号" name="idNo">
              <Input
                placeholder="请输入证件号"
                onBlur={(value) => {
                  checkHisPatInfo(value);
                }}
              />
            </Form.Item>
            <Form.Item label="性别" name="sex">
              <Radio.Group direction="horizontal">
                <Radio value="1">男</Radio>
                <Radio value="2">女</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="出生日期"
              name="dateOfBirth"
              // trigger="onConfirm"
              // // getValueFromEvent={(...args) => args[1]}
              onClick={(event, ref) => {
                event.stopPropagation();
                setTimeout(()=>{
                  setDatePickerVisible(true);
                },500)
            
              }}
            >
              <Input placeholder="请输入出生日期" />
            </Form.Item>
            <Form.Item label="手机号" name="homePhone">
              <Input placeholder="请输入手机号" type="phone" />
            </Form.Item>
          </Form>
        </view>

        <DatePicker
          title="日期选择"
          visible={datePickerVisible}
          value={form.getFieldValue("dateOfBirth")?new Date(form.getFieldValue("dateOfBirth")):new Date()}
          // defaultValue={new Date()}
          showChinese
          
          startDate={datePickerStartDate}
          endDate={new Date()}
          onClose={() => setDatePickerVisible(false)}
          onConfirm={(options, values) => {
        
            form.setFieldsValue({
              dateOfBirth: `${values[0]}-${values[1]}-${values[2]}`,
            });
          }}
        ></DatePicker>
      </view>
    </Layout>
  );
};
